// 每次请求前都要携带token 如果不带，服务器会报401的错误
import axios from 'axios'
import router from '../router/index'

let instance = axios.create({
    timeout: 60000,
    baseURL:'/api'
})
// 设置post请求头
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'

// 请求拦截---每次发起请求之前判断是否有token
// 如果有 将token保存在请求的header上
instance.interceptors.request.use(request => {
    // 从本地获取token
    let token = localStorage.getItem('token')
    // token为true（token有值）运行&&后面的语句 
    token && (request.headers['Authorization'] = `Bearer ${token}`)
    // token && (request.headers.common['Authorization'] = `Bearer ${token}`)
    return request
}, error => Promise.reject(error))
// 请求后
instance.interceptors.response.use(response => {
    // 获取token保存在本地
    // console.log(response)
    if (response.data.token) {
        localStorage.setItem('token', response.data.token)
    }
    return response
}, error => {
    console.log(error)
    let _response = error.response
    switch (_response.status) {
        case 401:
            localStorage.removeItem('token')
            return router.push('/login')
    }
    return Promise.reject(error.response.data)
})
export default instance